package com.woniu.humanresource.filter;

import com.woniu.humanresource.dao.UserDao;
import com.woniu.humanresource.entity.JWTUtil;
import com.woniu.humanresource.entity.LoginUserDetail;
import com.woniu.humanresource.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    UserDao userDao;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //如果token为空那就放行
        if(StringUtils.isEmpty(token)){
            filterChain.doFilter(request, response);
            return;
        }
        //token不正常  抛异常框架会自动处理
        if(!JWTUtil.verify(token)){
            new RuntimeException("token异常");
        }

        User user;
        try {
            //如果token正常拿到账号
            String uname = JWTUtil.getUname(token);
            //通过账号查出账号的信息
            user = userDao.selectUserByUname(uname);
            //查权限
            user.setPermission(userDao.selectPermissionByUname(uname));
        }catch (Exception e){
            throw new RuntimeException("账号错误");
        }
        //把信息和权限放到LoginUserDetail中
        LoginUserDetail loginUserDetail = new LoginUserDetail(user);
        //获取权限信息
        Collection<? extends GrantedAuthority> authorities = loginUserDetail.getAuthorities();
        //把user和权限信息放在认证信息中
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
        //认证信息放在
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}